package br.igk.isnmp.bean.oid.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;

import br.igk.hibernate.HibernateUtility;
import br.igk.isnmp.bean.oid.form.Oid;
import br.igk.isnmp.bean.oid.form.TipoOid;

@Service
public class TipoOidDaoImpl implements TipoOidDao {

	@Override
	public void add(TipoOid oid) throws Exception {
		try {
			HibernateUtility.openTransaction();
			getSession().save(oid);
			HibernateUtility.commit();
		} catch (Exception e) {
			HibernateUtility.rollback();
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TipoOid> list() throws Exception {
		try {
			HibernateUtility.openTransaction();
			return getSession().createCriteria(Oid.class).addOrder(Order.asc("id")).list();
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public void remove(Integer id) throws Exception {
		try {
			HibernateUtility.openTransaction();
			Oid oid = (Oid) getSession().load(Oid.class, id);
			if (oid != null)
				getSession().delete(oid);
			HibernateUtility.commit();
		} catch (Exception e) {
			HibernateUtility.rollback();
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void removeAll() throws Exception {
		try {
			HibernateUtility.openTransaction();
			List<Oid> list = getSession().createCriteria(Oid.class).list();
			for (Oid o : list)
				getSession().delete(o);
			HibernateUtility.commit();
		} catch (Exception e) {
			HibernateUtility.rollback();
			throw e;
		}
	}

	private Session getSession() {
		return HibernateUtility.getSession();
	}

	@Override
	public TipoOid get(Integer id) throws Exception {
		try {
			HibernateUtility.openTransaction();
			return (TipoOid)getSession().get(TipoOid.class, id);
		} catch (Exception e) {
			HibernateUtility.rollback();
			throw e;
		}
	}
}
